/**
 * Triangle Shape
 */
include(['shapes.Mesh', 'Vector2', 'shapes.Point'], 

function(){
	
	declare('shapes.Triangle');
	
	Triangle = Mesh.extend({
		init : function(p1, p2, p3){
			this._super(
				new Vector2(p1.x, p1.y)
				,new Vector2(p2.x, p2.y)
				,new Vector2(p3.x, p3.y)
			);
		},
		intersects : function( point, tolerance ){
			tolerance = tolerance | 1;
			var data = this._meshdata;				
			
			var a = this._dArea(data[0], data[1], point);
			var b = this._dArea(data[0], point, data[2]);
			var c = this._dArea(point, data[1], data[2]);
							
			var a1 = this._dArea(data[0], data[1], data[2]) | 0;
			var a2 = (a + b + c) |0;
			
			var i = a1 == a2;
			if( a1 > a2 && a1 - tolerance < a2 ) i =true;
			if( a1 < a2 && a1 + tolerance > a2 ) i =true;
			
			if( !a1 || !a2 ) i = false;
			
			var result = [];
			if( i )
				result.push(this);
			if( Point.intersection(data[0],point,tolerance) )
				result.push(data[0]);
			if( Point.intersection(data[1],point,tolerance) )
				result.push(data[1]);
			if( Point.intersection(data[2],point,tolerance) )
				result.push(data[2]);
			if( result.length == 0 ) 
				result = null;
			
			return result;
		},
		_dArea : function(a, b, c){
			return Math.abs(a.x*(b.y-c.y) + b.x*(c.y-a.y) + c.x*(a.y-b.y));
		},	
		toString : function(){
			var a = this.p1;
			var b = this.p2;
			var c = this.p3;
			return "a" + this._meshdata[0] +", b"+this._meshdata[1]+", c" +this._meshdata[2]
		},	
		area : function(){
			return this._dArea(data[0], data[1], data[2]) * 0.5;
		}
	}, 'Triangle');
});